package com.jetinno.utils;

import android.annotation.SuppressLint;
import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.util.Log;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class ContextHolder {
    private static final String TAG = "ContextHolder";

    private static Application mApplication = null;

    // 在自定义的Application中初始化.
    public static void init(Application application) {
        mApplication = application;
    }

    public static Resources getResources() {
        return getApplication().getResources();
    }

    // 发送普通的广播
    public static void sendBroadcast(Intent intent) {
        getApplication().sendBroadcast(intent);
    }

    public static Context getApplicationContext() {
        return getApplication().getApplicationContext();
    }

    public static Application getApplication() {
        if (mApplication != null) {
            return mApplication;
        }
        Application application = null;
        try {
            @SuppressLint("PrivateApi") Method method = Class.forName("android.app.ActivityThread").getDeclaredMethod("currentApplication");
            application = (Application) method.invoke(null, (Object) null);

            if (application == null) {
                @SuppressLint("PrivateApi") Method method1 = Class.forName("android.app.AppGlobals").getMethod("getInitialApplication");
                application = (Application) method1.invoke(null);
            }
        } catch (NoSuchMethodException | ClassNotFoundException | IllegalAccessException | InvocationTargetException e) {
            Log.e(TAG, e.toString());
        } finally {
            mApplication = application;
        }
        return mApplication;
    }

}
